package com.zxx.pattern.flyweight.fly1;

import java.util.HashMap;
import java.util.Map;

/**
 * 享元工厂：
 * @author zxx on 2021/7/16
 */
public class MyCharFactory {
    //单例
    private static volatile MyCharFactory instance;

    private Map<Character, MyChar> charMap;

    private MyCharFactory() {
        charMap = new HashMap<>();
    }

    //双重检索式
    public static MyCharFactory getInstance() {
        if (instance == null) {
            synchronized (MyCharFactory.class) {
                if (instance == null) {
                    instance = new MyCharFactory();
                }
            }
        }
        return instance;
    }

    /**
     * 根据字符的键获取字符对象
     */
    public MyChar getMyChar(Character c) {
        MyChar myChar = charMap.get(c);
        if (myChar == null) {
            myChar = new MyCharImpl(c);
            charMap.put(c, myChar);
        }
        return myChar;
    }

    /**
     * 获取Map中存储的字符的数量
     */
    public int getCharCount() {
        return charMap.size();
    }

}
